


import string
import random
import math
from PIL import Image, ImageDraw, ImageFont, ImageFilter

# 验证码图片大小
CAPTCHA_WIDTH = 120
CAPTCHA_HEIGHT = 50

# 随机生成字符串的函数
def random_string(length=4):
    """生成随机字符串"""
    candidates = string.ascii_letters + string.digits
    return ''.join(random.choice(candidates) for _ in range(length))

# 绘制干扰线的函数
def draw_lines(draw, num):
    """绘制干扰线"""
    for i in range(num):
        # 随机生成起点和终点
        x1 = random.randint(0, CAPTCHA_WIDTH)
        y1 = random.randint(0, CAPTCHA_HEIGHT)
        x2 = random.randint(0, CAPTCHA_WIDTH)
        y2 = random.randint(0, CAPTCHA_HEIGHT)
        # 随机生成线条颜色
        color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
        # 绘制直线
        draw.line((x1, y1, x2, y2), fill=color)

# 绘制验证码的函数
def draw_captcha(text):
    """绘制验证码"""
    image = Image.new('RGB', (CAPTCHA_WIDTH, CAPTCHA_HEIGHT), (255, 255, 255))
    draw = ImageDraw.Draw(image)
    font = ImageFont.truetype('ariblk.ttf', 36)
    text_width, text_height = draw.textsize(text, font=font)
    x = (CAPTCHA_WIDTH - text_width) / 2
    y = (CAPTCHA_HEIGHT - text_height) / 2
    # 绘制验证码文字
    draw.text((x, y), text, font=font, fill=(0, 0, 0))
    # 绘制干扰线
    draw_lines(draw, 5)
    # 模糊处理
    image = image.filter(ImageFilter.BLUR)
    return image

# 生成验证码并保存为图片的函数
def generate_captcha():
    """生成验证码图片并保存到本地"""
    text = random_string()
    image = draw_captcha(text)
    # 保存图片
    image.save('captcha.png')

if __name__ == '__main__':
    generate_captcha()
    print('验证码生成完成')